//
//  UIButton+Utilities.m
//  WaterPurifierProduct
//
//  Created by yc on 2017/11/4.
//  Copyright © 2017年 Cong Yao. All rights reserved.
//

#import "UIButton+Utilities.h"
#import <objc/runtime.h>

static const void *indexPathKey = &indexPathKey;
static dispatch_source_t timer = nil;

@implementation UIButton (Utilities)

- (NSString *)indexPath {
    return objc_getAssociatedObject(self, indexPathKey);
}

- (void)setIndexPath:(NSIndexPath *)indexPath {
    objc_setAssociatedObject(self, indexPathKey, indexPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
}



- (CGSize)btn_titleSize {
    CGSize size = CGSizeMake(MAXFLOAT, MAXFLOAT);
    CGSize _size;
    NSString *txt = self.titleLabel.text.length != 0 ? self.titleLabel.text : @"";
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    
    NSDictionary *attribute = @{NSFontAttributeName: self.titleLabel.font};
    
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine |
    
    NSStringDrawingUsesLineFragmentOrigin |
    
    NSStringDrawingUsesFontLeading;
    
    _size = [txt boundingRectWithSize:size options: options attributes:attribute context:nil].size;
    
#else
    
    _size = [txt sizeWithFont:font constrainedToSize:size];
    
#endif
    
    return _size;
}


- (void)addTimerWithSecond:(int)second palceHolder:(NSString *)placeHolder {
    __block int _code_out = second;
    __weak typeof(self) weakSelf = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (_code_out <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf setTitle:MyNSLocalizedString(@"获取验证码") forState:0];
                [weakSelf setTitle:[NSString stringWithFormat:@"%d%@",_code_out,MyNSLocalizedString(@"秒后获取")] forState:UIControlStateDisabled];
                weakSelf.enabled = YES;
                _code_out = 60;
            });
        } else {
            weakSelf.enabled = NO;
            NSString * time = [NSString stringWithFormat:MyNSLocalizedString(@"%d秒后获取"),_code_out];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf setTitle:time forState:UIControlStateDisabled];
            });
            _code_out--;
        }
    });
    dispatch_resume(timer);
}


- (void)cancelTimer {
    if (timer) {
        dispatch_source_set_cancel_handler(timer, nil);
    }
}
@end
